package com.javasm.controller;

import com.alibaba.fastjson.JSON;
import com.javasm.entity.Order;
import com.javasm.entity.PageInfo;
import com.javasm.entity.ReturnCodeEnum;
import com.javasm.entity.ReturnResult;
import com.javasm.service.OrderService;
import com.javasm.service.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/customerOrder/*")
public class OrderServlet extends BaseServlet{
    public void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1接收请求参数
        String pageStr = req.getParameter("page");
        String pageSizeStr = req.getParameter("pageSize");
        Integer page = 1;
        Integer pageSize = 10;
        if(pageStr!=null&&!"".equals(pageStr)){
            page = Integer.parseInt(pageStr);
        }
        if(pageSizeStr!=null&&!"".equals(pageSizeStr)){
            pageSize = Integer.parseInt(pageSizeStr);
        }
        String gameName = req.getParameter("gameName");
        String orderPaymentCustomerName = req.getParameter("orderPaymentCustomerName");
        String orderServeCustomerName = req.getParameter("orderServeCustomerName");
        String orderDatetime = req.getParameter("orderDatetime");
        String orderStatusStr = req.getParameter("orderStatus");
        Integer orderStatus = null;
        if(orderStatusStr!=null&&!"".equals(orderStatusStr)){
            orderStatus = Integer.parseInt(orderStatusStr);
        }
        Order inputOrder = new Order( orderDatetime, gameName, orderStatus, orderPaymentCustomerName, orderServeCustomerName);
        OrderService orderService = new OrderServiceImpl();
        Integer total = orderService.countCustomerOrder(inputOrder);

        Integer totalPage ;
        totalPage = total%pageSize==0?total/pageSize:total/pageSize+1;
        if(page!=1){
            if(page>totalPage){
                page = totalPage;
            }
        }
        List<Order> orders = orderService.listCustomerOrders(inputOrder, page, pageSize);
        PageInfo returnPageInfo = new PageInfo(page,pageSize,total);
        //3反馈操作结果
        ReturnResult rrs = new ReturnResult();
        if(orders.size()>0){
            rrs.setCode(ReturnCodeEnum.QUERY_SUCCESS.getCode());
            rrs.setMsg(ReturnCodeEnum.QUERY_SUCCESS.getMsg());

            rrs.setPageInfo(returnPageInfo);
            rrs.setReturnData(orders);
        }else{
            rrs.setCode(ReturnCodeEnum.QUERY_NODATA.getCode());
            rrs.setMsg(ReturnCodeEnum.QUERY_NODATA.getMsg());
        }
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.print(JSON.toJSONString(rrs));
        writer.close();


    }
}
